import datetime

from django.utils import timezone
from django.utils.dateparse import parse_date


def range_date(date_from, date_to):
    date = date_from
    while date <= date_to:
        yield date
        date += datetime.timedelta(days=1)

def add_8(dt):
    return dt + datetime.timedelta(hours=8)

def aware_localtime(dt):
    return add_8(dt.astimezone(timezone.utc))
# 241211，由于MongoDB中现在记录的是本时区的UTC时间,所以本时区的时间区间筛选,需要补充这个+8H差额


def as_datetime(date):
    if isinstance(date, datetime.datetime):
        return aware_localtime(date)
    try:
        return aware_localtime(datetime.datetime.combine(date, datetime.time.min))
    except Exception as e:
        return None


# 只适用于pg过滤
def date_filter(query_params, begin_param='date_from', end_param='date_to'):
    """从request参数字典中解析begin日期和end日期，返回date_from和date_to对象"""
    date_from = parse_date(query_params.get(begin_param, ''))
    date_to = parse_date(query_params.get(end_param, ''))
    return date_from, date_to


def date_filter_new(query_params, begin_param='date_from', end_param='date_to'):
    """从request参数字典中解析begin日期和end日期，返回date_from和date_to对象"""
    # 如果没有传日期，默认给最近一周的数据
    date_from = parse_date(query_params.get(begin_param, to_date(today_ago_many(days=7))))
    date_to = parse_date(query_params.get(end_param, to_date(today_ago_many())))
    return date_from, date_to


def today_ago_many(days=0):
    return datetime.date.today() - datetime.timedelta(days=days)


def yesterday():
    return datetime.date.today() - datetime.timedelta(days=1)


def now():
    return datetime.datetime.now()


def to_date(date_time):
    return date_time.strftime('%Y-%m-%d')
